package org.example.ims.Service.User;


import org.example.ims.Entity.Base.Salesman;
import org.example.ims.Entity.User.CustomUser;
import org.example.ims.Repository.Base.SalesmanRepository;
import org.example.ims.Repository.CustomUser.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service("CustomUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;     // 假设从数据库查用户

    private final PasswordEncoder passwordEncoder;

    private final SalesmanRepository salesmanRepository;

    @Autowired
    public CustomUserDetailsService(UserRepository userRepository,
                                    @Lazy PasswordEncoder passwordEncoder ,
                                    SalesmanRepository salesmanRepository) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
        this.salesmanRepository = salesmanRepository;
    }



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        CustomUser user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        // 打印用户信息用于调试（生产环境可删除）
        System.out.println("加载用户: " + username + ", 角色: " + user.getRoles());

        return user;
    }

    // 注册用户（添加 ROLE_ 前缀）
    public void registerUser(CustomUser user ,Integer salesmanId) {

        Salesman salesman = salesmanRepository.findById(salesmanId)
                .orElseThrow(() -> new RuntimeException("销售员（ID：" + salesmanId + "）不存在"));

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setEnabled(true);

        //关联业务员信息
        user.setSalesman(salesman);

        // 确保角色名以 ROLE_ 开头
        List<String> roles = user.getRoles().stream()
                .map(role -> role.startsWith("ROLE_") ? role : "ROLE_" + role)
                .collect(Collectors.toList());
        user.setRoles(roles);

        // 保存用户
        userRepository.save(user);

    }
}